import { apiPayPayWay, apiPayPrePay, apiWalletPay, apichargeOrder, apiH5PayPrePay } from '@/api/app'
import { wxpay } from '@/utils/pay'
import { toast, getClient } from '@/utils/util'
import { PayEnum, PayWayEnum, ClientEnum } from '@/utils/enum'
import { reactive, ref } from 'vue'

interface PaymentObj {
    from: string
    order_id: number | string
    cancelTime: string | number
    orderAmount: string
    payWayLists: any[]
    orderType: number | string
}

/**
 * @description 支付函数钩子
 * @return { Function } 暴露钩子
 */
export function usePay() {
    const loading = ref<boolean>(true)
    const lock = ref(true) //跳转锁
    let orderData: any = {} //订单数据
    // 支付对象
    const payment = reactive<PaymentObj>({
        from: '',
        order_id: '',
        cancelTime: 600,
        payWayLists: [] as any[],
        orderAmount: '',
        orderType: '' // 充值/订单
    })

    /**
     * @description 1. 初始化获取支付方式
     * @param { value } 需要支付的订单数据
     */
    const initPay = async (value: any): Promise<void> => {
        try {
            orderData = JSON.parse(decodeURIComponent(value))
            //获取支付方式列表
            const payLists = await apiPayPayWay({
                scene: getClient(),
                hidePayWay: orderData.type == PayEnum.RECHARGE ? 1 : ''
            })
            payment.orderType = orderData.type
            payment.order_id = orderData.id
            payment.cancelTime = parseInt(String(orderData.orderExpireTime - new Date().getTime()))
            payment.payWayLists = payLists
            payment.orderAmount = orderData.totalAmount
            loading.value = false
        } catch (err) {
            console.log(err)
            toast('支付方式' + err)
        }
    }

    /**
     * @description 2. 支付
     * @param { pay_way } 支付方式
     */
    const handlePayPrepay = async (
        pay_way: number,
        couponAmount: any,
        couponId: any,
        integralPirce?: any,
        integralVal?: any
    ): Promise<void> => {
        try {
            let res: any

            if (pay_way == PayWayEnum.WECHAT) {
                //微信支付
                if (payment.orderType == PayEnum.ORDER) {
                    //订单
                    if (getClient() != ClientEnum.H5) {
                        //小程序、公众号支付
                        res = await apiPayPrePay({
                            orderId: payment.order_id,
                            couponDiscountPrice: couponAmount,
                            receiveId: couponId,
                            integralDiscountPrice: integralPirce,
                            integralVal,
                            terminal: getClient()
                        })
                    } else {
                        //h5支付
                        const url = await apiH5PayPrePay({
                            orderId: payment.order_id,
                            couponDiscountPrice: couponAmount,
                            receiveId: couponId,
                            integralDiscountPrice: integralPirce,
                            integralVal
                        })
                        res.url = url
                    }
                } else if (payment.orderType == PayEnum.RECHARGE) {
                    //充值
                    res = await apichargeOrder({
                        orderId: payment.order_id,
                        terminal: getClient()
                    })
                }
            }
            let result: any = null
            // 支付
            switch (pay_way * 1) {
                //钱包支付
                case PayWayEnum.WALLET:
                    result = await handleWalletPay(
                        couponAmount,
                        couponId,
                        integralPirce,
                        integralVal
                    )
                    break
                //微信支付
                case PayWayEnum.WECHAT:
                    result = await handleWechatPay(res)
                    break
                default:
                    throw '支付方式不对'
            }
            setTimeout(() => {
                handlePayResult(result, pay_way)
            }, 500)
        } catch (err: any) {
            // toast(err)
            console.log('预支付', err)
        }
    }

    /**
     * @description 微信支付
     * @param { params } 支付订单
     */
    const handleWechatPay = async (params: any): Promise<boolean> => {
        try {
            await wxpay(params)
            return true
        } catch (err) {
            toast('支付取消')
            console.log('支付失败', err)
            return false
        }
    }

    /**
     * @description 钱包支付
     */
    const handleWalletPay = async (
        couponAmount: number,
        couponId: number,
        integralPirce: any,
        integralVal: any
    ): Promise<boolean> => {
        try {
            await apiWalletPay({
                orderId: payment.order_id,
                couponDiscountPrice: couponAmount,
                receiveId: couponId,
                integralDiscountPrice: integralPirce,
                integralVal
            })
            return true
        } catch (err) {
            console.log(err)
            return false
        }
    }

    /**
     * @description 3. 支付结果
     * @param { result } 支付结果
     * @param {pay_way} 支付方式
     */
    const handlePayResult = (result = false, pay_way?: any) => {
        if (lock.value) {
            if (getClient() != ClientEnum.H5) {
                //非H5环境支付
                //支付失败
                if (result == false) {
                    if (payment.orderType == PayEnum.RECHARGE) {
                        return
                    }
                    //钱包支付失败不跳转
                    else if (pay_way == PayWayEnum.WALLET) {
                        return
                    }
                    uni.redirectTo({
                        url: `/bundle/pages/pay_result/index?orderId=${payment.order_id}&type=${payment.orderType}`
                    })

                    return
                }
                uni.navigateTo({
                    url: `/bundle/pages/pay_result/index?orderId=${payment.order_id}&type=${payment.orderType}`
                })
            } else if (getClient() == ClientEnum.H5) {
                //h5钱包支付
                if (pay_way == PayWayEnum.WALLET)
                    uni.reLaunch({
                        url: `/bundle/pages/pay_result/index?orderId=${payment.order_id}`
                    })
            }
            lock.value = false
        }
        return
    }

    return {
        loading,
        payment,
        initPay,
        handlePayPrepay,
        handlePayResult
    }
}
